import { MinusCircleOutlined } from '@ant-design/icons-vue'
import {
  Button,
  Form,
  FormItem,
  Image,
  Input,
  InputNumber,
  message,
  Spin,
  Textarea
} from 'ant-design-vue'
import { defineComponent, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'

import { commonApi } from '@/apis'
import qzyApi from '@/apis/qzyApi'
import { goodsItem, qzyCombinationItem, qzyOrderItem } from '@/apis/qzyType'
import { type ProEditorRef, ProEditor, ProEditorProps } from '@/components'
import UploadFile from '@/components/UploadFile'
import { useBack } from '@/hooks'
import { isValueEmpty } from '@/utils'
import SelectYxGoods from '@/views/marketing/yxGoodsManage/hook/selectYxGoods'

export default defineComponent({
  name: 'QzyGoodsEdit',
  setup() {
    const selectGoodsRef = ref({} as any)
    const goodsData = ref([] as any)
    const loading = ref(false)
    const visible = ref(false)
    const deleteVisible = ref(false)
    const route = useRoute()
    const id = ref(route.query.id)
    const showExpressDlg = ref(false)
    const { handleCancel } = useBack('refreshFormationList')
    const expressInfo = ref({} as qzyCombinationItem)
    const editorRef = ref({} as ProEditorRef)
    const editorConfig = ref({
      wrapStyle: {
        width: '702px'
      },
      editorStyle: {
        height: '350px'
      },
      editorHtml: '',
      editorVisible: false,
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            server: commonApi.uploadFileUrl,
            fieldName: 'file',
            customInsert(res: any, insertFn: any) {
              // res 即服务端的返回结果
              const url = res.data
              // 从 res 中找到 url alt href ，然后插图图片
              insertFn(url, '', '')
            },
            maxFileSize: 10 * 1024 * 1024,
            onError(file: File, err: any, res: any) {
              if (file && file.size > 10 * 1024 * 1024) {
                message.error('图片超过10M，请压缩图片或分段上传')
              }
            }
          }
        } as any
      },
      toolbarConfig: {
        excludeKeys: ['group-video']
      }
    } as ProEditorProps)
    //编辑详情详情
    async function getDetail() {
      if (id.value) {
        loading.value = true
        try {
          const data = await qzyApi.qzyCombinationDetail({ id: id.value })
          expressInfo.value = data
          expressInfo.value.combinationItemCommandList =
            data.combinationItemVoList
          delete expressInfo.value.combinationItemVoList
          editorConfig.value.editorHtml = expressInfo.value.detail
          editorConfig.value.editorVisible = true
          numPrice.value = expressInfo.value.totalPrice
        } finally {
          loading.value = false
          console.log(expressInfo.value.combinationItemCommandList)
          goodsData.value = expressInfo.value.combinationItemCommandList || []
          console.log(goodsData.value)
        }
      } else {
        editorConfig.value.editorVisible = true
      }
    }

    //商品更改
    function onGoodsClick() {
      selectGoodsRef.value.show()
    }
    //商品选中
    function onGoodsSelect(item) {
      console.log(item)
      if (item.stock < 0) {
        message.error('库存不足')
        return
      }
      if (item.salePrice === 0) {
        message.error('商品价格为0')
        return
      }
      const data = [] as any
      Object.assign(data, item)
      goodsData.value.push(data)
    }
    const numPrice = ref(0)
    // 计算总价
    function handleSumPrice() {
      let sum: any = 0
      goodsData.value.forEach((k: any) => (sum += k.salePrice * k.num))
      // numPrice.value = numPrice.value + item.salePrice
      numPrice.value = sum
    }
    //商品赋值
    function handleGoods() {
      const arr = [] as any
      console.log(goodsData.value)
      goodsData.value.map((k: any) => {
        arr.push({
          goodsId: k.goodsId,
          goodsName: k.goodsName,
          num: k.num,
          specId: k.id || k.specId
        })
      })
      expressInfo.value.combinationItemCommandList = arr
    }
    //保存或编辑
    async function handleConfirm() {
      handleGoods()
      console.log(expressInfo.value.combinationItemCommandList)
      //数据校验
      if (isValueEmpty(expressInfo.value.combinationItemCommandList)) {
        message.error('商品组合不能为空')
        return
      } else {
        for (const i in expressInfo.value.combinationItemCommandList) {
          if (
            isValueEmpty(expressInfo.value.combinationItemCommandList[i].num)
          ) {
            message.error('商品组合不能为空')
            return
          }
        }
      }
      if (isValueEmpty(expressInfo.value.title)) {
        message.error('商品主标题不能为空')
        return
      }
      if (isValueEmpty(expressInfo.value.salePrice)) {
        message.error('优惠价不能为空')
        return
      }
      if (isValueEmpty(expressInfo.value.imgMain)) {
        message.error('商品主图不能为空')
        return
      }

      editorConfig.value.editorVisible = true
      const editorHtml = editorRef.value.editor.getHtml()
      expressInfo.value.detail = editorHtml
      editorConfig.value.editorVisible = true
      console.log(expressInfo.value)
      if (id.value) {
        //编辑
        try {
          await qzyApi.editQzyCombination(expressInfo.value).then(() => {
            // handleCancel()
            message.success('保存成功')
            handleCancel()
          })
        } finally {
        }
      } else {
        //新增
        try {
          await qzyApi.createQzyCombination(expressInfo.value).then(() => {
            // handleCancel()
            message.success('保存成功')
            handleCancel()
          })
        } finally {
        }
      }
    }
    function cancel() {
      handleCancel()
    }
    onMounted(() => {
      getDetail()
      // expressInfo.value.combinationItemCommandList = [] as goodsItem[]
    })
    return {
      goodsData,
      selectGoodsRef,
      showExpressDlg,
      expressInfo,
      numPrice,
      visible,
      loading,
      editorConfig,
      editorRef,
      deleteVisible,
      cancel,
      handleCancel,
      handleSumPrice,
      getDetail,
      onGoodsClick,
      onGoodsSelect,
      handleConfirm
    }
  },
  render() {
    return (
      <Spin spinning={this.loading}>
        <Form labelCol={{ span: 2 }}>
          <FormItem label="组合主标题:" required>
            <Input
              v-model:value={this.expressInfo.title}
              maxlength={25}
              style={{ width: '300px', marginLeft: '10px' }}
            ></Input>
          </FormItem>
          <FormItem label="组合副标题:">
            <Textarea
              v-model:value={this.expressInfo.titleExt}
              maxlength={40}
              style={{ width: '300px', marginLeft: '10px' }}
            ></Textarea>
          </FormItem>
          <FormItem label="商品组合:" required>
            {this.goodsData?.map((k, index) => (
              <div v-show={k.goodsName} style={{ marginBottom: '25px' }}>
                <span v-show={k.mainImg}>
                  <Image
                    src={k.mainImg}
                    style={{
                      width: '75px',
                      height: '50px',
                      marginLeft: '10px'
                    }}
                  ></Image>
                </span>
                <span v-show={k.prizeUrl}>
                  <Image
                    src={k.prizeUrl}
                    style={{
                      width: '75px',
                      height: '50px',
                      marginLeft: '10px'
                    }}
                  ></Image>
                </span>
                <span style={{ marginLeft: '15px', marginRight: '35px' }}>
                  {k.goodsName}
                </span>
                <span>数量*</span>
                <InputNumber
                  v-model:value={k.num}
                  style={{
                    marginLeft: '15px',
                    marginRight: '15px',
                    width: '60px'
                  }}
                  onChange={this.handleSumPrice}
                  min={1}
                ></InputNumber>
                <MinusCircleOutlined
                  onClick={() => this.goodsData.splice(index, 1)}
                />
              </div>
            ))}
            <Button
              type="primary"
              style={{ marginLeft: '10px' }}
              onClick={this.onGoodsClick}
            >
              添加单品
            </Button>
          </FormItem>
          <FormItem label="套餐总价:">
            <InputNumber
              v-model:value={this.numPrice}
              style={{ width: '88px', marginLeft: '10px', marginRight: '5px' }}
              precision={2}
              min={0}
              disabled
            ></InputNumber>
            {`元`}
          </FormItem>
          <FormItem label="套餐优惠价:" required>
            <InputNumber
              v-model:value={this.expressInfo.salePrice}
              style={{ width: '88px', marginLeft: '10px', marginRight: '5px' }}
              precision={2}
              min={0}
            ></InputNumber>
            {`元`}
          </FormItem>
          <FormItem label="商品主图:" required>
            <div style={{ marginLeft: '10px' }}>
              <UploadFile v-model={[this.expressInfo.imgMain, 'urls']}>
                上传图片
              </UploadFile>
            </div>
          </FormItem>
          <FormItem label="商品轮播图:">
            <div style={{ marginLeft: '10px' }}>
              <UploadFile
                v-model={[this.expressInfo.imgList, 'urls']}
                maxLength={10}
              >
                上传图片
              </UploadFile>
            </div>
          </FormItem>
          <FormItem label="商品详情信息:">
            <ProEditor
              style={{ width: '720px', height: '500px' }}
              ref="editorRef"
              {...this.editorConfig}
            />
          </FormItem>
          <FormItem
            style={{
              marginLeft: '200px',
              marginTop: '30px',
              marginBottom: '50px'
            }}
          >
            <Button
              style={{ width: '200px', height: '45px', marginRight: '100px' }}
              onClick={this.cancel}
            >
              取消
            </Button>
            <Button
              type="primary"
              style={{ width: '200px', height: '45px' }}
              onClick={this.handleConfirm}
            >
              保存
            </Button>
          </FormItem>
        </Form>
        <SelectYxGoods
          ref="selectGoodsRef"
          goodsPlatform={1}
          status={1}
          onSelect={this.onGoodsSelect}
        />
      </Spin>
    )
  }
})
